package com.khson.knows.portal.service.impl;

import com.khson.knows.portal.mapper.UserMapper;
import com.khson.knows.portal.model.Permission;
import com.khson.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名获取用户信息
        User user = userMapper.findUserByUsername(username);
        //2.判断用户名是否存在
        if(user==null){
            //用户不存在
            return null;
        }
        //3.查询当前用户所有权限
        List<Permission> permissions = userMapper.findUserPermissionsById(user.getId());
        //4.转换权限List为String[]
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (Permission permission:permissions) {
            auth[i++] = permission.getName();
        }
        //5.构建UserDetails对象用户返回
        UserDetails u = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                //设置当前用户的所有的权限/资格
                .authorities(auth)
                /*
                Spring-Security支持用户的锁定和禁用,
                (账号密码输入错误多次则锁定,违规则禁用(封号))需要在User表中添加字段
                */
                // 设置禁用,()里是真表示锁定,否则不锁
                .accountLocked(user.getLocked()==1)
                //设置可用,()里是真表示禁用,否则可用
                .disabled(user.getEnabled()==0)
                .build();
        //6.返回UserDetails对象
        return u;
    }
}
